<template>
  <van-form class="mt-60" @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
      <van-button round block type="primary" @click="gototally">
        gototallyselect
      </van-button>
      <van-button round block type="primary" @click="gotoRetreat">
        retreat
      </van-button>
    </div>
  </van-form>
  <van-field v-model="text" label="文本" placeholder="请输入用户名" />
</template>

<script setup lang="ts" name="Login">
import { ref } from "vue";
import MD5 from "md5";
import { loginSystem } from "@/api/blade";
import { useToken } from "@/store/token";
import router from "@/router";
import { GetAreaId } from "@/api/common";
import { showFailToast } from "vant";
import { useDictInfo } from "@/store/dict";

const username = ref("");
const password = ref("");
const text = ref("");

function gototally() {
  router.push("/tally-type-select");
}
function gotoRetreat() {
  router.push("/retreat-view-select");
}
function onSubmit(values: any) {
  const postdata = {
    grant_type: "password",
    username: values.username,
    password: MD5(values.password)
  };
  loginSystem(new URLSearchParams(postdata).toString()).then((res: any) => {
    const tokenStore = useToken();
    const dictStore = useDictInfo();
    dictStore.clearAllDict();
    tokenStore.removeToken();
    tokenStore.setToken(res.access_token);
    localStorage.clear();
    localStorage.setItem("token", res.access_token);

    GetAreaId().then((res: any) => {
      if (!res.data) {
        showFailToast("该账号未绑定区域");
      } else {
        tokenStore.setAreaId(res.data as string);
        localStorage.setItem("areaId", res.data as string);
        dictStore.initAllDict();
      }
    });
  });
};
</script>
